<template>
  <div v-if="readonly" class="deptNames">
    <span v-for="i in deptName" :key="i">{{ i }}</span>
  </div>
  <el-cascader
    v-else
    v-model="chioseKey"
    :options="depts"
    :placeholder="placeholder"
    :props="props"
    :clearable="clearable"
    :disabled="disabled"
    class="el-input"
    @change="handleChange"
  />
</template>

<script>
import { getDeptTree, GetNameList } from '@/api/unit/unit'
import { GetName } from '@/api/base/company'
import store from '@/store'
export default {
  props: {
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '选择部门'
    },
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isUnit: {
      type: Boolean,
      default: null
    },
    status: {
      type: Array,
      default: () => [1]
    },
    companyId: {
      type: String,
      default: () => {
        return store.getters.curComId
      }
    },
    isMultiple: {
      type: Boolean,
      default: false
    },
    isChioseUnit: {
      type: Boolean,
      default: true
    },
    unitId: {
      type: String,
      default: null
    },
    isDept: {
      type: Boolean,
      default: null
    },
    value: {
      // eslint-disable-next-line vue/require-prop-type-constructor
      type: String | Array,
      default: null
    },
    label: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      depts: [],
      chioseKey: null,
      dept: {},
      deptName: [],
      name: null,
      cid: null,
      props: {
        multiple: false,
        emitPath: false,
        checkStrictly: true,
        value: 'Id',
        label: 'Name',
        children: 'Children'
      }
    }
  },
  computed: {
    comName() {
      const comId = this.$store.getters.curComId
      return this.$store.getters.company[comId]
    },
    comId() {
      return this.$store.getters.curComId
    }
  },
  watch: {
    companyId: {
      handler(val) {
        if (this.readonly === false) {
          this.reset()
        }
      },
      immediate: true
    },
    isMultiple: {
      handler(val) {
        this.props.multiple = this.isMultiple
      },
      immediate: false
    },
    isUnit: {
      handler(val) {
        if (!this.readonly) {
          this.loadTree()
        }
      },
      immediate: false
    },
    isChioseUnit: {
      handler(val) {
        this.resetConfig()
      },
      immediate: false
    },
    unitId: {
      handler(val) {
        this.reset()
      },
      immediate: false
    },
    value: {
      handler(val) {
        if (val == null) {
          this.chioseKey = null
        } else if (!Array.isArray(val)) {
          this.chioseKey = typeof val === 'number' ? val.toString() : val
        } else {
          this.chioseKey = val
        }
        if (this.readonly) {
          this.reset()
        } else {
          this.loadLabel()
        }
      },
      immediate: true
    },
    readonly: {
      handler(val) {
        if (val && this.value != null) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  methods: {
    resetConfig() {
      if (this.depts && this.depts.length > 0) {
        this.depts.forEach((c) => {
          this.format(c)
        })
      }
    },
    reset() {
      this.cid =
        this.companyId === '' || this.companyId == null
          ? this.comId
          : this.companyId
      if (this.readonly) {
        if (this.chioseKey == null) {
          this.deptName = []
          return
        } else if (this.isMultiple && this.chioseKey.length !== 0) {
          this.loadName(this.chioseKey)
        } else if (this.isMultiple === false && this.chioseKey !== '0') {
          this.loadName([this.chioseKey])
        } else {
          this.deptName = []
        }
      } else {
        this.deptName = []
        this.name = null
        this.loadTree()
      }
    },
    loadLabel() {
      let label = null
      if (this.value != null) {
        if (this.isMultiple && Array.isArray(this.value)) {
          label = this.formatName(this.value)
        } else if (this.dept[this.value] != null) {
          label = this.dept[this.value].Name
        }
      }
      this.$emit('update:label', label)
    },
    formatName(list) {
      let name = ''
      list.forEach(c => {
        name = ',' + this.dept[c].Name
      })
      return name.substring(1)
    },
    async GetComName() {
      if (this.name !== null) {
        return this.name
      } else if (this.cid === this.comId) {
        this.name = this.comName
      } else {
        const name = this.$store.getters.company[this.cid]
        if (name) {
          this.name = name
        } else {
          this.name = await GetName(this.cid)
        }
      }
      return this.name
    },
    async loadName(ids) {
      this.deptName = await GetNameList(ids)
      this.$emit('update:label', this.deptName.join(','))
    },
    async loadTree() {
      const res = await getDeptTree({
        CompanyId: this.cid,
        Status: this.status,
        UnitId: this.unitId,
        IsUnit: this.isUnit,
        IsDept: this.isDept
      })
      this.props.multiple = this.isMultiple
      this.dept = {}
      if (res && res.length > 0) {
        res.forEach((c) => {
          this.dept[c.Id] = c
          this.format(c)
        })
        this.depts = res
        if (this.value !== null && this.isMultiple === false) {
          this.chioseKey =
              typeof this.value === 'number'
                ? this.value.toString()
                : this.value
        }
        this.loadLabel()
      } else {
        this.depts = []
      }
    },
    format(row) {
      if (row.IsUnit && !this.isChioseUnit) {
        row.disabled = true
      }
      if (row.Children.length === 0) {
        row.Children = null
      } else {
        row.Children.forEach((c) => {
          this.dept[c.Id] = c
          this.format(c)
        })
      }
    },
    async handleChange(val) {
      const comName = await this.GetComName()
      const e = {
        isMultiple: this.isMultiple,
        companyId: this.cid,
        comName: comName,
        value: [],
        dept: []
      }
      let label = null
      if (val != null) {
        if (this.isMultiple) {
          e.value = val
          e.dept = val.map((c) => this.dept[c])
          label = e.dept.map(c => c.Name).join(',')
        } else if (val) {
          e.value = [val]
          e.dept = [this.dept[val]]
          label = this.dept[val].Name
        } else {
          e.value = []
          e.dept = []
        }
      }
      this.$emit('update:label', label)
      this.$emit('input', val)
      this.$emit('change', e)
    }
  }
}
</script>
<style scoped>
.deptNames {
  display: inline-block;
  line-height: 20px;
}
.deptNames span {
  padding: 5px;
}
</style>
